<template>
  <div class="">
    <h2>图书馆里</h2>
    书名：<input type="text" v-model="title" /> 价格：<input
      type="text"
      v-model="price"
    />
    <button @click="add">操作</button>
    <hr />
    <table>
      <tr>
        <th>编号</th>
        <th>标题</th>
        <th>价格</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item, index) in list" :key="item.id">
        <td>{{ item.id }}</td>
        <td>{{ item.title }}</td>
        <td>{{ item.price }}</td>
        <td>
          <button @click="edit(item, index)">修改</button>
          <button @click="remove(index)">删除</button>
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [
        {
          id: 1,
          title: "vuejs从入门到放弃",
          price: 100,
        },
        {
          id: 2,
          title: "猪八戒背媳妇",
          price: 200,
        },
        {
          id: 3,
          title: "三国演义",
          price: 300,
        },
      ],
      isedit: false,
      //是否修改的状态
      title: "",
      price: "",
      editindex: -1,
      //保存要修改的数据的下标
    };
  },
  mounted() {},
  methods: {
    add() {
      if (this.isedit == false) {
        this.list.push({
          id: this.list.length + 1,
          title: this.title,
          price: this.price,
        });
      } else {
        this.list[this.editindex].title = this.title;
        this.list[this.editindex].price = this.price;
        this.isedit = false;
      }
      this.title = "";
      this.price = "";
    },
    //点击操作按钮的时候 判断 isedit的状态 如果是false证明没有编辑，往里添加  else的时候证明正处于编辑的状态，根据当前编辑的下标修改数据
    remove(i) {
      this.list.splice(i, 1);
    },
    //删除
    edit(item, index) {
      this.isedit = true;
      //点击修改的时候把 修改状态变成 true
      this.title = item.title;
      this.price = item.price;
      //数据回填
      this.editindex = index;
      //把要修改的数据的下标保存 为了后期点击操作修改数据
    },
  },
  components: {},
};
</script>

<style lang="scss"></style>
